import cd from '/api/cartData.js';
import rfb from '/components/right-fixed-bar.js';
(() => {
    render()
    $('.search-btn').on('click', function() {
        const key = $('.search-key').val();
        location.href = '/pages/list.html?' + (key ? "q=" + key : "title=" + $('.search-key').attr('placeholder'));
    })
})()
/* 生成购物车 */
function render() {
    cd.getCart(data => {
        // console.log(data);
        if (data == "noData") {
            $('.mycart .ci-count').text(0);
            $('.mycart .nogoods').html(`
                <b></b>购物车中还没有商品，赶紧选购吧！
            `);
        } else if (data == 'err') {
            $('.mycart .ci-count').text(0);
            $('.mycart .nogoods').html(`
                <b></b>请登录！
            `);
        } else {
            // console.log(data);
            // let str = ``;
            // data.forEach(el => {
            //     const p = el[1];
            //     str += `
            // <div class="mycart_item">
            //     <a href="/pages/detial.html?pid=${p.pid}">
            //         <img src="${p.imgsrc}" />
            //     </a>
            //     <p>${p.name}</p>
            //     <span>
            //         ${el[0]}
            //     </span>
            //     <span class="remove_item" data-id="${p.pid}">X</span>
            // </div>
            // `;
            // })
            // $('.mycart .nogoods').html(str);
            /* 渲染搜索框右侧购物车 */
            $('.mycart .nogoods').html(data.map(el => {
                return `
                <div class="mycart_item">
                    <a href="/pages/detial.html?pid=${el[1].pid}">
                        <img src="${el[1].imgsrc}" />
                    </a>
                    <p>${el[1].name}</p>
                    <span>
                        ${el[0]}
                    </span>
                    <span class="remove_item" data-id="${el[1].pid}">X</span>
                </div>
                `;
            }));
            /* 渲染搜索框右侧购物车角标 */
            $('.mycart .ci-count').text(data.length);
            /* 添加购物车商品删除事件 */
            $('.remove_item').off('click').on('click', function() {
                // console.log($(this).data('id'));
                cd.del($(this).data('id'), (shopping_amount) => {
                    $('.mycart .ci-count').text(shopping_amount);
                    /* 删除完后重新渲染购物车 */
                    render();
                    rfb.render();
                });
            })
            /* 设置角标单击事件 */
            $('.mycart .cw-icon').off('click').on('click', () => {
                location.href = "/pages/cart.html"
            })
        }
    })
}

function getKey() {
    return decodeURIComponent(location.search.split('=')[1]);
}
export default {
    render
}